var ToolReplaceTableInit = function(){
    var oTableInit = {};
    //初始化Table
    oTableInit.Init = function () {
        $('#toolReplaceTable').bootstrapTable({
            url: ctx +'/tool/replace/getToolConfigByFilter/get.mvc',         //请求后台的URL（*）
            method: 'get',                      //请求方式（*）
//            toolbar: '#toolbar',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            paginationLoop:false,
            sortable: true,                     //是否启用排序
            sortOrder: "asc",                   //排序方式
            queryParams: oTableInit.queryParams,//传递参数（*）
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber:1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            strictSearch: true,
            showColumns: false,                  //是否显示所有的列
            showRefresh: false,                  //是否显示刷新按钮
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            height: 500,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            uniqueId: "pkId",                     //每一行的唯一标识，一般为主键列
            showToggle:false,                    //是否显示详细视图和列表视图的切换按钮
            cardView: false,                    //是否显示详细视图
            detailView: false,                   //是否显示父子表
            singleSelect:false,                    //禁止多选
            checkboxHeader:true,                 //列头取消多选
            columns: [
                {
                    checkbox:true,
                    align : 'center',
                    valign : 'middle'
                },
                {
                    title: '序号',
                    align : 'center',
                    valign : 'middle',
                    formatter : function (value, row, index){
                        var options = $('#toolReplaceTable').bootstrapTable('getOptions');
                        return options.pageSize * (options.pageNumber - 1) + index + 1;
                    }
                }, {
                    field: 'toolCode',
                    title: '工装编码',
                    sortable:false,
                    align : 'center',
                    valign : 'middle'
                }, {
                    field: 'toolName',
                    title: '工装名称',
                    sortable:false,
                    align : 'center',
                    valign : 'middle'
                },{
                    field: 'toolModel',
                    title: '工装型号',
                    sortable:false,
                    align : 'center',
                    valign : 'middle'
                }, {
                    field: 'toolTypeValue',
                    title: '工装类别',
                    sortable:false,
                    align : 'center',
                    valign : 'middle'

                }, {
                    field: 'replaceDate',
                    title: '更换时间',
                    sortable:false,
                    align : 'center',
                    valign : 'middle'

                }, {
                    field: 'replaceUser',
                    title: '更换人',
                    sortable:false,
                    align : 'center',
                    valign : 'middle'

                }, {
                    field: 'replaceReason',
                    title: '更换原因',
                    sortable:false,
                    align : 'center',
                    valign : 'middle'

                }, {
                    field: 'pkId',
                    title: 'pkId',
                    visible:false
                }]

        });
    };
    //得到查询的参数
    oTableInit.queryParams = function (params) {
        return {   // 这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            size: params.limit,   // 页面大小
            num: (params.offset/params.limit) + 1,  // 页码
            sort: params.sort,
            order: params.order,
            equipCode:$("#equipList").find("li.active").data("equipcode")
            //modelId:modelId
        }
    };
    return oTableInit;
};

jQuery(document).ready(function() {
    //初始化页面
    toolReplaceInit.init();
});



var toolReplaceInit = function() {
    var userSelect2;
    return {
        init:function() {
            toolReplaceInit._initEquipList();
            toolReplaceInit._modalHidden();
            toolReplaceInit._initToolReplaceTable();
            toolReplaceInit._validatorForm();
            toolReplaceInit._validatorUpdateForm();
            toolReplaceInit._query();
            toolReplaceInit._keyQuery();
            toolReplaceInit._refresh();
            toolReplaceInit._add();
            toolReplaceInit._replace();
            toolReplaceInit._initDateControl();
            toolReplaceInit._save();
            toolReplaceInit._update();
            toolReplaceInit._getToolInfo();
            toolReplaceInit._initCheckbox();
            userSelect2 = toolReplaceInit._initReplaceUserSelect2();
        },
        //条件查询
        _query:function() {
            $("#eqSearch").on("click",function(){
                toolReplaceInit._initEquipList()
            });
        },
        //按键查询
        _keyQuery:function() {
            $(".eq-search").keypress(function (e) {
                if (e.which === 13) {
                    $("#eqSearch").trigger("click");
                }
            });
        },
        _refresh : function(){
            //刷新
            $("#refreshTable").on("click",function(){
                $('#toolReplaceTable').bootstrapTable('refresh');
            });
        },
        _initEquipList:function () {
            var equipCode = $("#equipCode").val();
            $.ajax({
                url : ctx + '/tool/replace/getEquipList/get.mvc',
                type : "post",
                dataType : 'json',
                data : {
                    equipCode:equipCode
                },
                success : function(response) {
                    //debugger;
                    if (response.result === true&&response.data) {
                        var eqList = response.data;
                        var equipList = $("#equipList");
                        equipList.empty();
                        for (var i = 0;i<eqList.length;i++) {
                            var li = $("<li class='eq-equip' data-equipcode='"+eqList[i].equipCode+"'>"+eqList[i].equipName+"</li>");
                            equipList.append(li);
                        }
                    } else {
                        DialogUtil.error(response.message);
                    }

                },
                error : function(XMLHttpRequest, textStatus, errorThrown) {
                    console.log(errorThrown);
                    DialogUtil.error("系统错误");
                }
            });
        },
        _initDateControl:function () {
            $('.form_datetime').datetimepicker({
                format : 'yyyy-mm-dd hh:ii:00',
                language : 'zh-CN',
                autoclose: true,
                pickerPosition: "bottom-left",
                //endDate : new Date(),
                forceParse : true
            }).on('hide', function(event) {
                event.preventDefault();
                event.stopPropagation();
            });
        },
        _initToolReplaceTable:function () {
            var oTable = new ToolReplaceTableInit();
            oTable.Init();
            $("#equipList").on("click","li",function (e) {
                e.preventDefault();
                $(this).addClass("active").siblings().removeClass("active");
                var equipCode = $(this).data("equipcode");
                console.log(equipCode);
                $('#toolReplaceTable').bootstrapTable('refreshOptions',{
                    pageNumber:1
                });
            });
        },
        //checkbox单选
        _initCheckbox : function () {
            $('#toolReplaceForm input[type="checkbox"]').each(function(){
                $(this).click(function(){
                    if($(this).is(":checked")){
                        $('#toolReplaceForm input[type="checkbox"]').prop("checked",false);
                        $(this).prop("checked",true);
                    }
                });
            });
        },
        //新增
        _add : function() {
            $("#add").on('click', function(e) {
                e.preventDefault();
                $('#myModal .title').html("新增");
                $("#modelFormCode").val($("#eqModelList").find("li.active").data("modelcode"));
                var equipCode = $("#equipList").find("li.active").data("equipcode");
                if(!equipCode) {
                    DialogUtil.warning("请先选择设备");
                    return;
                }
                toolReplaceInit._initToolCodeSelect();
                $("#toolAddForm").find("input[name=equipCode]").val($("#equipList").find("li.active").data("equipcode"));
                $('#toolAddModal').modal();
            });
        },
        _replace: function () {
            $("#replace").on("click",function (e) {
                e.preventDefault();
                $('#myModal .title').html("更换");
                var ids = $.map($('#toolReplaceTable').bootstrapTable('getSelections'), function (row) {
                    return row.pkId;
                });
                if (ids.length !== 1 ) {
                    DialogUtil.warning("请选择一个工装进行更换");
                    return false;
                }
                toolReplaceInit._initToolCodeReplaceSelect();
                var row = $.map($('#toolReplaceTable').bootstrapTable('getSelections'), function (row) {
                    return row;
                });
                //解决select2无法输入问题
                $.fn.modal.Constructor.prototype.enforceFocus = function() {
                    $("#myModal select").focus();
                };
                console.log(row[0].pkId);
                console.log(row[0].toolCode);
                $("#toolReplaceForm").find("input[name=pkId]").val(row[0].pkId);
                $("#toolReplaceForm").find("input[name=originToolCode]").val(row[0].toolCode);
                //默认用户为当前登录人
                toolReplaceInit._setReplaceUser();
                $('#myModal').modal();
            });
        },
        _initReplaceUserSelect2 :function () {
            var select2 = $('#replaceUser').select2({
                ajax: {
                    url: ctx +'/system/user/getSysUserList/get.mvc',
                    dataType: 'json',
                    aynsc :false,
                    data: function (params) {
                        // Query parameters will be ?search=[term]&page=[page]
                        return {
                            search: params.term,
                            num: params.page || 1,
                            size: 10
                        };
                    },
                    processResults: function (response) {
                        // Tranforms the top-level key of the response object from 'items' to 'results'
                        var test =[];
                        if(response.result === true&&response.data){
                            var _data = response.data;
                            for ( var int = 0; int < _data.length; int++) {
                                var obj={};
                                obj.id=_data[int].username;
                                obj.text=_data[int].truename;
                                test.push(obj);
                            }
                            return {
                                results: test
                            };
                        }
                        return null;
                    },
                    // Additional AJAX parameters go here; see the end of this chapter for the full code of this example
                    cache: true

                },
                placeholder: '请选择',
                language: "zh-CN",
                escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
                minimumInputLength: 0
            });
            return select2;
        },
        _setReplaceUser : function () {
            $.ajax({
                url : ctx + '/system/user/getCurrentUser/get.mvc',
                type : "post",
                dataType : 'json',
                success : function(response) {
                    //debugger;
                    if (response.result === true && response.data) {
                        var _data = response.data;
                        var username = _data.username;
                        var truename = _data.truename;
                        if(truename!==''&&username!=='') {
                            var option = new Option(truename,username,true,true);
                            userSelect2.append(option);
                            userSelect2.trigger("change");
                        }
                    } else {
                        DialogUtil.error(response.message);
                    }

                },
                error : function(XMLHttpRequest, textStatus, errorThrown) {
                    console.log(errorThrown);
                    DialogUtil.error("系统错误");
                }
            });
        },
        _initToolCodeSelect:function () {
            $.ajax({
                url: ctx +'/tool/replace/getToolList/get.mvc',
                type:"post",
                aysnc: false,
                dataType:'json',
                data : {
                    equipCode:$("#equipList").find("li.active").data("equipcode")
                },
                success : function(response){
                    if (response.result === true) {
                        if(response.data) {
                            var _data = response.data;
                            $("#toolAddForm select[name=toolCode]").empty();
                            $("#toolAddForm select[name=toolCode]").append("<option value=''>请选择</option>");
                            for (var i = 0; i < _data.length; i++) {
                                $("#toolAddForm select[name=toolCode]").append("<option value='"+_data[i].pkId+"' >" + _data[i].toolCode + "</option>");
                            }
                        }
                    } else {
                        DialogUtil.error(response.message);
                    }

                },
                error : function(XMLHttpRequest, textStatus, errorThrown) {
                    console.log(errorThrown);
                    DialogUtil.error("系统错误");
                }
            });
        },
        _initToolCodeReplaceSelect:function () {
            $.ajax({
                url: ctx +'/tool/replace/getToolList/get.mvc',
                type:"post",
                aysnc: false,
                dataType:'json',
                data : {
                    equipCode:$("#equipList").find("li.active").data("equipcode")
                },
                success : function(response){
                    if (response.result === true) {
                        if(response.data) {
                            var _data = response.data;
                            $("#toolReplaceForm select[name=toolCode]").empty();
                            $("#toolReplaceForm select[name=toolCode]").append("<option value=''>请选择</option>");
                            for (var i = 0; i < _data.length; i++) {
                                $("#toolReplaceForm select[name=toolCode]").append("<option value='"+_data[i].pkId+"' >" + _data[i].toolCode + "</option>");
                            }
                        }
                    } else {
                        DialogUtil.error(response.message);
                    }

                },
                error : function(XMLHttpRequest, textStatus, errorThrown) {
                    console.log(errorThrown);
                    DialogUtil.error("系统错误");
                }
            });
        },
        //工装编码下拉框change查询工装信息
        _getToolInfo:function () {
            $("#toolCodeAddSelect").on("change",function (e) {
                e.preventDefault();
                var toolId = $("#toolCodeAddSelect").val();
                console.log(toolId);
                $.ajax({
                    url: ctx + '/tool/toolInfo/getToolInfoById/get.mvc',
                    type:"post",
                    dataType:'json',
                    data : {
                        pkId : toolId
                    },
                    success : function(response){
                        console.log(response);
                        if (response.result === true ) {
                            var _data = response.data;
                            if(_data) {
                                $("#toolAddForm").find("input[name=toolName]").val(_data.toolName);
                                $("#toolAddForm").find("input[name=toolModel]").val(_data.toolModel);
                                $("#toolAddForm").find("input[name=toolType]").val(_data.toolTypeValue);
                            }

                        }else {
                            DialogUtil.error(response.message);
                        }
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown){
                        DialogUtil.error(errorThrown);
                    }
                });
            });
            $("#toolCodeReplaceSelect").on("change",function (e) {
                e.preventDefault();
                var toolId = $("#toolCodeReplaceSelect").val();
                console.log(toolId);
                $.ajax({
                    url: ctx + '/tool/toolInfo/getToolInfoById/get.mvc',
                    type:"post",
                    dataType:'json',
                    data : {
                        pkId : toolId
                    },
                    success : function(response){
                        console.log(response);
                        if (response.result === true ) {
                            var _data = response.data;
                            if(_data) {
                                $("#toolReplaceForm").find("input[name=toolName]").val(_data.toolName);
                            }
                        }else {
                            DialogUtil.error(response.message);
                        }
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown){
                        DialogUtil.error(errorThrown);
                    }
                });
            })
        },
        //删除
        _delete : function () {
            $("#delete").on("click", function(){
                var ids = $.map($('#toolReplaceTable').bootstrapTable('getSelections'), function (row) {
                    return row.pkId;
                });
                if (ids.length <1 ) {
                    DialogUtil.warning("请选择需要删除的记录");
                    return false;
                }
                DialogUtil.ok_and_cancel("是否确定删除记录？",function(){
                    $.ajax({
                        url: ctx + '/tool/config/deleteToolConfigById/del.mvc',
                        type:"post",
                        dataType:'json',
                        data : {
                            pkIds : ids.toString()
                        },
                        success : function(response){
                            console.log(response);
                            if (response.result === true) {
                                DialogUtil.warning("删除成功");
                                $('#toolReplaceTable').bootstrapTable('refresh');
                            }else {
                                DialogUtil.error(response.message);
                            }
                        },
                        error: function(XMLHttpRequest, textStatus, errorThrown){
                            DialogUtil.error(errorThrown);
                        }
                    });
                },function(){

                });
            });
        },
        //修改
        //表单校验
        _validatorForm : function () {
            $("#toolAddForm").bootstrapValidator({
                message: 'This value is not valid',
                live: 'submitted',
                fields: {/*验证*/
                    toolCode: {
                        message: '工装编码无效',
                        validators: {
                            notEmpty: {
                                message: '工装编码不能为空'
                            }
                        }
                    }
                }
            });
        },
        _validatorUpdateForm : function () {
            $("#toolReplaceForm").bootstrapValidator({
                message: 'This value is not valid',
                live: 'submitted',
                fields: {/*验证*/
                    toolCode: {
                        message: '工装编码无效',
                        validators: {
                            notEmpty: {
                                message: '新工装编码不能为空'
                            }
                        }
                    },
                    toolName: {
                        message: '工装名称无效',
                        validators: {
                            notEmpty: {
                                message: '新工装名称不能为空'
                            }
                        }
                    },
                    replaceUser: {
                        message: '更换人无效',
                        validators: {
                            notEmpty: {
                                message: '更换人不能为空'
                            }
                        }
                    },
                    replaceDate: {
                        trigger:'change',
                        message: '更换时间无效',
                        validators: {
                            notEmpty: {
                                message: '更换时间不能为空'
                            }
                        }
                    },
                    replaceReason: {
                        message: '更换原因无效',
                        validators: {
                            notEmpty: {
                                message: '更换原因不能为空'
                            },
                            stringLength: {
                                max: 30,
                                message: '更换原因不能超过30个字符'
                            }
                        }
                    },
                    remark: {
                        message: '备注无效',
                        validators: {
                            stringLength: {
                                max: 50,
                                message: '备注不能超过50个字符'
                            }
                        }
                    }
                }
            });
        },
        //保存
        _save : function () {
            $("#toolAddModal .yes").on("click",function (e) {
                $("#toolAddModal .yes").attr("disabled",true);
                e.preventDefault();
                $("#toolAddForm").data("bootstrapValidator").validate();
                var flag = $("#toolAddForm").data("bootstrapValidator").isValid();
                if(!flag){
                    $("#toolAddModal .yes").attr("disabled",false);
                    //未通过验证
                    return false;
                }
                var entity = {};
                entity['toolCode'] = $("#toolAddForm").find("select[name=toolCode]").find("option:selected").text();
                entity['equipCode'] = $("#toolAddForm").find("input[name=equipCode]").val();
                console.log(entity);
                $.ajax({
                    url : ctx + '/tool/replace/saveEqToolConfig/save.mvc',
                    type : "post",
                    dataType : 'json',
                    data : entity,
                    success : function(response) {
                        if (response.result === true) {
                            DialogUtil.ok("保存成功");
                            //取消
                            $('#toolAddModal').modal('hide');
                            $('#toolReplaceTable').bootstrapTable('refresh');
                        } else {
                            DialogUtil.error(response.message);
                        }
                        $("#toolAddModal .yes").attr("disabled",false);

                    },
                    error : function(XMLHttpRequest, textStatus, errorThrown) {
                        $("#toolAddModal .yes").attr("disabled",false);
                        console.log(errorThrown);
                        DialogUtil.error("系统错误");
                    }
                });

            });
        },
        _update : function () {
            $("#myModal .yes").on("click",function (e) {
                $("#myModal .yes").attr("disabled",true);
                e.preventDefault();
                $("#toolReplaceForm").data("bootstrapValidator").validate();
                var flag = $("#toolReplaceForm").data("bootstrapValidator").isValid();
                if(!flag){
                    $("#myModal .yes").attr("disabled",false);
                    //未通过验证
                    return false;
                }
                var entity = {};
                entity['pkId'] = $("#toolReplaceForm").find("input[name=pkId]").val();
                entity['equipCode'] = $("#equipList").find("li.active").data("equipcode");
                entity['originToolCode'] = $("#toolReplaceForm").find("input[name=originToolCode]").val();
                entity['toolCode'] = $("#toolReplaceForm").find("select[name=toolCode]").find("option:selected").text();
                entity['replaceDate'] = $("#toolReplaceForm").find("input[name=replaceDate]").val();
                entity['replaceUser'] = $("#toolReplaceForm").find("select[name=replaceUser]").val();
                entity['replaceReason'] = $("#toolReplaceForm").find("input[name=replaceReason]").val();
                entity['remark'] = $("#toolReplaceForm").find("input[name=remark]").val();
                if($("#toolReplaceForm").find("input[name=repair]").is(":checked")) {
                    entity['repair'] = '1';
                }
                if($("#toolReplaceForm").find("input[name=scrap]").is(":checked")) {
                    entity['scrap'] = '1';
                }
                console.log(entity);
                $.ajax({
                    url : ctx + '/tool/replace/replaceTool/save.mvc',
                    type : "post",
                    dataType : 'json',
                    data : entity,
                    success : function(response) {
                        if (response.result === true) {
                            DialogUtil.ok("保存成功");
                            //取消
                            $('#myModal').modal('hide');
                            //$('#toolReplaceTable').bootstrapTable('refresh');
                            toolRepairInit._refreshTable();
                        } else {
                            DialogUtil.error(response.message);
                        }
                        $("#myModal .yes").attr("disabled",false);

                    },
                    error : function(XMLHttpRequest, textStatus, errorThrown) {
                        $("#myModal .yes").attr("disabled",false);
                        console.log(errorThrown);
                        DialogUtil.error("系统错误");
                    }
                });

            });
        },
        _modalHidden : function () {
            //模态框消失清空信息
            $("#myModal").on("hide.bs.modal",function(){
                $('#myModal input').each(function() {
                    if ($(this).val() !== "" ) {
                        $(this).val("");
                    }
                });
                $('#myModal input[type=checkbox]').each(function() {
                    if ($(this).val() !== "" ) {
                        $(this).val("");
                    }
                });
                $('#toolReplaceForm input[type="checkbox"]').prop("checked",false);
                $("#toolCodeSelect2").val(null).trigger("change");
                $('#toolReplaceForm').bootstrapValidator('resetForm', false);
            });

            $("#toolAddModal").on("hide.bs.modal",function(){
                $('#toolAddModal input').each(function() {
                    if ($(this).val() !== "" ) {
                        $(this).val("");
                    }
                });
                $("#toolCodeAddSelect").val("");
                $('#toolAddForm').bootstrapValidator('resetForm', false);
            });
        }
    }
}();